package com.mind.adjust.service.impl;

import com.mind.adjust.mapper.AjRuleCheckMapper;
import com.mind.adjust.mapper.AjRuleDetailMapper;
import com.mind.adjust.service.AjRuleService;
import com.mind.api.serivce.ITongweiMessage;
import com.mind.common.core.domain.model.LoginUser;
import com.mind.common.exception.ServiceException;
import com.mind.common.utils.DateUtils;
import com.mind.common.utils.SecurityUtils;
import com.mind.common.utils.StringUtils;
import com.mind.common.utils.uuid.UUID;
import com.mind.customer.mapper.AjRuleMapper;
import com.mind.system.domain.AjRule;
import com.mind.system.domain.AjRuleCheck;
import com.mind.system.domain.AjRuleDetail;
import com.mind.system.domain.SysConfig;
import com.mind.system.mapper.SysConfigMapper;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
 * 规则配置(AjRule)表服务实现类
 *
 * @author makejava
 * @since 2024-07-15 15:35:21
 */
@Service("ruleService")
public class AjRuleServiceImpl implements AjRuleService {
    @Autowired
    private AjRuleMapper ruleMapper;
    @Autowired
    private AjRuleDetailMapper ruleDetailMapper;
    @Autowired
    private AjRuleCheckMapper ruleCheckMapper;

    @Resource
    private ITongweiMessage tongweiMessage;

    @Resource
    private SysConfigMapper sysConfigMapper;


    /**
     * 查询规则配置信息集合
     *
     * @param rule 规则配置信息
     * @return 规则配置信息集合
     */
    @Override
    public List<AjRule> selectRuleList(AjRule rule) {
        List<AjRule> ruleList = ruleMapper.selectRuleList(rule);
        for (AjRule r : ruleList) {
            AjRuleDetail ajRuleDetail = ruleDetailMapper.selectRuleDetailById(r.getRuleDetailId());
            if (ajRuleDetail != null) {
                r.setRuleDetailName(ajRuleDetail.getName());
            }
        }
        return ruleList;
    }

    /**
     * 通过规则配置ID查询规则配置信息
     *
     * @param ruleId 规则配置ID
     * @return 角色对象信息
     */
    @Override
    public AjRule selectRuleById(Long ruleId) {
        return ruleMapper.selectRuleById(ruleId);
    }

    /**
     * 删除规则配置信息
     *
     * @param ruleId 规则配置ID
     * @return 结果
     */
    @Override
    public int deleteRuleById(Long ruleId) {
        return ruleMapper.deleteRuleById(ruleId);
    }

    /**
     * 批量删除规则配置信息
     *
     * @param ruleIds 需要删除的规则配置ID
     * @return 结果
     */
    @Override
    public int deleteRuleByIds(Long[] ruleIds) {
        return ruleMapper.deleteRuleByIds(ruleIds);
    }

    /**
     * 新增保存规则配置信息
     *
     * @param rule 规则配置信息
     * @return 结果
     */
    @Override
    public int insertRule(AjRule rule) {

        int count = 0;
        SysConfig sysConfig = sysConfigMapper.checkConfigKeyUnique("checkEnable");
        if ("1".equals(sysConfig.getConfigValue())) {

            //setRuleStatus(rule);
            String oldStatus = rule.getStatus();
            // 新增状态为
            String[] status = getStatusBySubmit(rule.getStatus(), "1");
//        rule.setStatus("3");
            if (rule.getActiveDate() != null) {
                if (rule.getActiveDate().getTime() < DateUtils.localDateToTimestamp(LocalDate.now())) {
                    throw new ServiceException("生效日期不能小于当前日期");
                }
            }
            if (rule.getExpireDate() != null && rule.getActiveDate() != null) {
                if (rule.getExpireDate().getTime() < rule.getActiveDate().getTime()) {
                    throw new ServiceException("失效日期不能小于生效日期");
                }
            }
            rule.setIsAdd("1");
            rule.setStatus(status[0]);
            rule.setUuid(UUID.fastUUID().toString().replaceAll("-", ""));
            count += ruleMapper.insertRule(rule);
            addCheck(rule, status[1], StringUtils.isEmpty(oldStatus) ? "20" : oldStatus, null);
        } else {
            rule.setIsAdd("1");
            rule.setStatus("1");
            rule.setUuid(UUID.fastUUID().toString().replaceAll("-", ""));
            count += ruleMapper.insertRule(rule);
        }
        return count;
    }

    private String[] getStatusBySubmit(String status, String isAdd) {
        if ("1".equals(isAdd)) {
            if ("20".equals(status)) {
                return new String[]{"3", "1"};
            } else if ("21".equals(status)) {
                return new String[]{"8", "2"};
            }
        } else {
            if ("20".equals(status)) {
                return new String[]{"3", "1"};
            } else if ("21".equals(status)) {
                return new String[]{"4", "2"};
            } else if ("22".equals(status)) {
                return new String[]{"6", "5"};
            } else if ("23".equals(status)) {
                return new String[]{"5", "未使用"};
            }
        }
        throw new ServiceException(String.format("不支持的状态【%s】", status));

    }

    /**
     * 添加复核
     *
     * @param rule
     * @param flag
     */
    public void addCheck(AjRule rule, String flag, String status, AjRule oldRule) {

        AjRuleCheck check = new AjRuleCheck();
        if (rule.getRuleDetailName() == null) {
            rule = ruleMapper.selectRuleById(rule.getId().longValue());
        }
        BeanUtils.copyProperties(rule, check);
        check.setRuleStatus(status.equals("23") ? "5" : status);
        check.setStatus(flag);
        check.setRuleId(rule.getId());
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser != null) {
            check.setSubmitor(loginUser.getUsername());
            check.setSubmitorId(loginUser.getUserId().intValue());
        }
        check.setCreateTime(DateUtils.getNowDate());    // 创建日期
        check.setUpdateTime(DateUtils.getNowDate());    // 更新日期
        if (Arrays.asList("21", "22").contains(status)) {
            check.setSubmitTime(new Date());
        }
        sendMessage(status, rule);
        copyRuleDetail(rule, check);
        // 添加复核数据
        ruleCheckMapper.insertRuleCheck(check);
        if (!status.equals("23") && !rule.getIsAdd().equals("1")) {
            AjRuleCheck ajRuleCheck = new AjRuleCheck();
            BeanUtils.copyProperties(oldRule, ajRuleCheck);
            copyRuleDetail(oldRule, ajRuleCheck);
            ajRuleCheck.setRuleId(rule.getId());
            ajRuleCheck.setRuleStatus("1");
            ajRuleCheck.setStatus("7");
            ruleCheckMapper.insertRuleCheck(ajRuleCheck);
        }

    }

    private void sendMessage(String status, AjRule rule) {
        if (Arrays.asList("21", "22").contains(status)) {
            String msg = String.format("【%s】提交了【%s】", SecurityUtils.getLoginUser().getUser().getNickName(), rule.getRuleDetailName());
        }
    }

    private void copyRuleDetail(AjRule rule, AjRuleCheck check) {
        if (rule.getRuleDetailId() != null) {
            AjRuleDetail detail = ruleDetailMapper.selectRuleDetailById(rule.getRuleDetailId());
            if (detail == null) {
                throw new ServiceException("未找到该规则明细");
            }
            check.setRuleDetailId(detail.getId().longValue());
            check.setRuleDetailAlert(detail.getAlert());
            check.setRuleDetailEditor(detail.getEditor());
            check.setRuleDetailRuleGroup(detail.getRuleGroup());
            check.setRuleDetailAttachCate(detail.getAttachCate());
            check.setRuleDetailDesc(detail.getDesc());
        }

    }


    /**
     * 修改保存规则配置信息
     *
     * @param rule 规则配置信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateRule(AjRule rule) {
        SysConfig sysConfig = sysConfigMapper.checkConfigKeyUnique("checkEnable");
        if (sysConfig != null && "1".equals(sysConfig.getConfigValue())) {
            if (StringUtils.isEmpty(rule.getStatus())) {
                throw new ServiceException("状态不能为空");
            }

            //setRuleStatus(rule);
            AjRule oldRule = ruleMapper.selectRuleById(rule.getId().longValue());
            if (oldRule == null) {
                throw new ServiceException("未找到该规则配置");
            }
            if (Arrays.asList("5", "2").contains(oldRule.getStatus())) {
                throw new ServiceException("该规则已作废或已失效，不允许修改");
            }

//            if (Arrays.asList("3").contains(oldRule.getStatus())) {
//                throw new ServiceException("该规则已经失效，不允许修改");
//            }
            AjRule newRule = new AjRule() {{
                setId(rule.getId());
            }};

            if (rule.getActiveDate() != null) {
                if (rule.getActiveDate().getTime() < DateUtils.localDateToTimestamp(LocalDate.now())) {
                    throw new ServiceException("生效日期不能小于当前日期");
                }
            }
            if (rule.getExpireDate() != null && rule.getActiveDate() != null) {
                if (rule.getExpireDate().getTime() < rule.getActiveDate().getTime()) {
                    throw new ServiceException("失效日期不能小于生效日期");
                }
            }

            String[] status = getStatusBySubmit(rule.getStatus(), oldRule.getIsAdd());
            // 作废
            if (Arrays.asList("5").contains(status[0])) {

                if (oldRule.getStatus().equals("7") && !oldRule.getIsAdd().equals("1")) {
                    addCheck(rule, "8", "23", oldRule);
                    newRule.setStatus("1");
                } else {
                    newRule.setStatus(status[0]);
                }
                List<AjRuleCheck> ajRuleChecks = ruleCheckMapper.selectRuleCheckList(new AjRuleCheck() {{
                    setRuleId(rule.getId());
                    setStatusNames("1");
                }});
                if (!CollectionUtils.isEmpty(ajRuleChecks)) {
                    ruleCheckMapper.updateRuleCheck(new AjRuleCheck() {{
                        setId(ajRuleChecks.get(0).getId());
                        setStatus("8");
                        setRuleStatus("3");
                    }});
                    List<AjRuleCheck> ajRuleCheckList = ruleCheckMapper.selectRuleCheckList(new AjRuleCheck() {{
                        setRuleId(rule.getId());
                        setStatusNames("7");
                    }});
                    // 删除之前生效的版本
                    if (!CollectionUtils.isEmpty(ajRuleCheckList)) {
                        for (AjRuleCheck check : ajRuleCheckList) {
                            ruleCheckMapper.deleteRuleCheckById(check.getId().longValue());
                        }
                    }
                } else {
                    ruleMapper.updateRule(newRule);
                }

            }
            // 失效
            else if ("22".equals(rule.getStatus())) {
                if (StringUtils.isNotNull(oldRule.getExpireDate()) && oldRule.getExpireDate().getTime() > DateUtils.localDateToTimestamp(LocalDate.now())) {
                    newRule.setStatus("6");
                } else {
                    newRule.setStatus("2");
                }

                ruleMapper.updateRule(newRule);
                List<AjRuleCheck> ajRuleCheckList = ruleCheckMapper.selectRuleCheckList(new AjRuleCheck() {{
                    setRuleId(rule.getId());
                    setStatusNames("1,2");
                }});
                for (AjRuleCheck check : ajRuleCheckList) {
                    ruleCheckMapper.deleteRuleCheckById(check.getId().longValue());
                }
            }
            // 编辑
            else {
                if (Arrays.asList("9").contains(oldRule.getStatus())) {
                    throw new ServiceException("该规则即将生效，不允许修改");
                }
                // 规则配置新增逻辑
                if (oldRule.getIsAdd().equals("1")) {
                    ruleMapper.updateRule(rule);
                }
                if (!CollectionUtils.isEmpty(ruleCheckMapper.selectRuleCheckList(new AjRuleCheck() {{
                    setRuleId(rule.getId());
                    setStatusNames("2");
                }}))) {
                    throw new ServiceException("该规则配置在复核中,请勿重复修改提交。");
                }
                // 状态为暂存
                List<AjRuleCheck> ajRuleChecks = ruleCheckMapper.selectRuleCheckList(new AjRuleCheck() {{
                    setRuleId(rule.getId());
                    setStatusNames("1");
                }});


                if (CollectionUtils.isEmpty(ajRuleChecks)) {
//                    newRule.setStatus(status[0]);
//                    ruleMapper.updateRule(newRule);
                    addCheck(rule, status[1], rule.getStatus(), oldRule);
                } else {
//                    newRule.setStatus(status[0]);
//                    ruleMapper.updateRule(newRule);
                    AjRuleCheck check = new AjRuleCheck();
                    BeanUtils.copyProperties(rule, check);
                    if (Arrays.asList("21", "22").contains(rule.getStatus())) {
                        check.setSubmitTime(new Date());
                    }
                    copyRuleDetail(rule, check);
                    // 获取当前的用户
                    LoginUser loginUser = SecurityUtils.getLoginUser();
                    if (loginUser != null) {
                        check.setSubmitor(loginUser.getUsername());
                        check.setSubmitorId(loginUser.getUserId().intValue());
                    }
                    check.setStatus(status[1]);
                    check.setId(ajRuleChecks.get(0).getId());
                    ruleCheckMapper.updateRuleCheck(check);
                    sendMessage(rule.getStatus(), rule);
                }
            }
        } else {
            switch (rule.getStatus()) {

                case "23":
                    //  作废
                    rule.setStatus("5");
                    break;
                case "22":
                    //  失效
                    rule.setStatus("2");
                    break;
                case "1":
                    //   生效

                    break;
                default:
                    rule.setStatus(null);
                    break;
            }
          /*  String[] status = getStatusBySubmit(rule.getStatus(), rule.getIsAdd());
            rule.setStatus(status[0]);*/
            ruleMapper.updateRule(rule);
        }
        return 1;
    }


    public void setRuleStatus(AjRule rule) {
        if (rule.getActiveDate() != null && rule.getActiveDate().before(new Date())) {
            rule.setStatus("1");
        }
        if (rule.getExpireDate() != null && rule.getExpireDate().after(new Date())) {
            rule.setStatus("2");
        }
    }

    /**
     * 批量插入
     *
     * @param ruleList 附件类型信息
     * @return 结果
     */
    @Override
    public int batchInsert(List<AjRule> ruleList) {
        int size = 0;
        for (AjRule rule : ruleList) {
            if (ruleMapper.selectRuleByName(rule.getName()) == null) {
                ruleMapper.insertRule(rule);
                size++;
            }
        }
        return size;
    }

    //    /**
//     * 修改状态
//     * @param id
//     */
    @Override
    public int updateStatus(Long id, String status) {
//        AjRule rule = ruleMapper.selectRuleById(id);
//        if(rule!= null) {
//            if(status.equals("2")) {
//                addCheck(rule, "2");
//                ruleMapper.updateRule(new AjRule(){{
//                    setId(id.intValue());
//                    setStatus(status);
//                    setUpdateTime(new Date());
//                }});
//                return 1;
//            }else{
//                rule.setStatus(status);
//                return ruleMapper.updateRule(rule);
//            }
//        }
        return 0;
    }

    @Override
    public AjRule findByRuleId(Long ruleId) {
        List<AjRuleCheck> ajRuleChecks = ruleCheckMapper.selectRuleCheckList(new AjRuleCheck() {{
            setRuleId(ruleId.intValue());
            setStatusNames("1");
        }});
        if (ajRuleChecks.size() > 0) {
            AjRule rule = new AjRule();
            BeanUtils.copyProperties(ajRuleChecks.get(0), rule);
            return rule;
        }
        return ruleMapper.selectRuleById(ruleId);
    }

}
